<?php
declare (strict_types=1);

namespace app\middleware;

use app\constants\HttpStatus;
use app\constants\ServiceStatus;
use app\traits\ResponseTrait;

class Before
{
    use ResponseTrait;

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //定义header头
        $header = $request->header();
        //获取需要进行token验证的url
        $authUrl = config('authurl');
        //获取header中的Token
        $token = isset($header["token"]) ? $header["token"] : "";
        //获取当前请求的url
        $currentUrl = $request->url();
        //需要进行验证token的url判断
        //var_dump(strtolower($currentUrl)  , array_map('strtolower',$authUrl), '----' ,in_array(strtolower($currentUrl), array_map('strtolower',$authUrl)));
        if (in_array(strtolower($currentUrl), array_map('strtolower',$authUrl))) {
            // 验证Token
            $check = app("jwt")->checkToken($token);
            if ($check["code"] == 1001) {
                $this->error(ServiceStatus::TOKEN_SIGNATURE_INVALID["CODE"], ServiceStatus::TOKEN_SIGNATURE_INVALID["MESSAGE"], HttpStatus::UNAUTHORIZED["CODE"]);
            }
            if ($check["code"] == 1002) {
                $this->error(ServiceStatus::TOKEN_BEFORE_VALID["CODE"], ServiceStatus::TOKEN_BEFORE_VALID["MESSAGE"], HttpStatus::UNAUTHORIZED["CODE"]);
            }
            if ($check["code"] == 1003) {
                $this->error(ServiceStatus::TOKEN_EXPIRED["CODE"], ServiceStatus::TOKEN_EXPIRED["MESSAGE"], HttpStatus::UNAUTHORIZED["CODE"]);
            }
            if ($check["code"] == 1004) {
                $this->error(ServiceStatus::TOKEN_EXCEPTION["CODE"], ServiceStatus::TOKEN_EXCEPTION["MESSAGE"], HttpStatus::UNAUTHORIZED["CODE"]);
            }
        }
        return $next($request);
    }
}
